<template>
  <div class="student-points-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="points-list-card">
          <template #header>
            <div class="card-header">
              <span>学生学习积分列表</span>
              <div class="header-actions">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索学生姓名或用户名"
                  style="width: 300px; margin-right: 10px;"
                  @keyup.enter="searchStudents"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
                <el-button type="primary" @click="searchStudents">搜索</el-button>
              </div>
            </div>
          </template>

          <el-table
            :data="students"
            style="width: 100%"
            stripe
            v-loading="loading"
            @sort-change="handleSortChange"
          >
            <el-table-column
              prop="id"
              label="用户ID"
              width="100"
              sortable="custom"
            />
            <el-table-column
              prop="username"
              label="用户名"
              width="150"
            />
            <el-table-column
              prop="name"
              label="姓名"
              width="150"
            />
            <el-table-column
              prop="studyPoints"
              label="学习积分"
              width="120"
              sortable="custom"
            >
              <template #default="scope">
                <span class="points-value">{{ scope.row.studyPoints || 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="studyLevel"
              label="学习等级"
              width="100"
            >
              <template #default="scope">
                <el-tag>Lv.{{ scope.row.studyLevel || 1 }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="200"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="viewStudentDetail(scope.row)"
                >
                  查看详情
                </el-button>
                <el-button
                  type="success"
                  size="small"
                  @click="adjustPoints(scope.row)"
                  style="margin-left: 10px;"
                >
                  调整积分
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50]"
              :total="totalStudents"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 调整积分对话框 -->
    <el-dialog
      v-model="adjustPointsDialogVisible"
      title="调整学习积分"
      width="500px"
    >
      <el-form
        :model="pointsAdjustForm"
        :rules="pointsAdjustRules"
        ref="pointsAdjustFormRef"
        label-width="100px"
      >
        <el-form-item label="学生姓名">
          <el-input v-model="pointsAdjustForm.studentName" disabled />
        </el-form-item>
        <el-form-item label="当前积分">
          <el-input v-model="pointsAdjustForm.currentPoints" disabled />
        </el-form-item>
        <el-form-item label="调整类型" prop="adjustType">
          <el-select v-model="pointsAdjustForm.adjustType" placeholder="请选择调整类型">
            <el-option label="增加" value="ADD" />
            <el-option label="减少" value="SUBTRACT" />
          </el-select>
        </el-form-item>
        <el-form-item label="调整积分" prop="points">
          <el-input-number
            v-model="pointsAdjustForm.points"
            :min="1"
            :max="10000"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="调整原因" prop="reason">
          <el-input
            v-model="pointsAdjustForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入调整积分的原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adjustPointsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPointsAdjustment">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import request from '../../utils/request'

// 数据
const students = ref([])
const loading = ref(false)
const searchKeyword = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const totalStudents = ref(0)

// 排序
const sortField = ref('')
const sortOrder = ref('')

// 调整积分对话框
const adjustPointsDialogVisible = ref(false)
const pointsAdjustForm = ref({
  studentId: 0,
  studentName: '',
  currentPoints: 0,
  adjustType: 'ADD',
  points: 10,
  reason: ''
})

// 表单引用
const pointsAdjustFormRef = ref()

// 表单验证规则
const pointsAdjustRules = {
  adjustType: [
    { required: true, message: '请选择调整类型', trigger: 'change' }
  ],
  points: [
    { required: true, message: '请输入调整积分', trigger: 'blur' }
  ],
  reason: [
    { required: true, message: '请输入调整原因', trigger: 'blur' }
  ]
}

// 获取学生列表
const fetchStudents = async () => {
  loading.value = true
  try {
    const response = await request.get('/api/study/students', {
      params: {
        page: currentPage.value - 1,
        size: pageSize.value,
        keyword: searchKeyword.value,
        sortField: sortField.value,
        sortOrder: sortOrder.value
      }
    })
    students.value = response.data.content
    totalStudents.value = response.data.totalElements
  } catch (error) {
    ElMessage.error('获取学生列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索学生
const searchStudents = () => {
  currentPage.value = 1
  fetchStudents()
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchStudents()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchStudents()
}

// 处理排序变化
const handleSortChange = (sort: any) => {
  sortField.value = sort.prop
  sortOrder.value = sort.order === 'ascending' ? 'ASC' : 'DESC'
  fetchStudents()
}

// 查看学生详情
const viewStudentDetail = (student: any) => {
  ElMessage.info(`查看学生 ${student.name} 的详细信息功能待开发`)
}

// 调整积分
const adjustPoints = (student: any) => {
  pointsAdjustForm.value = {
    studentId: student.id,
    studentName: student.name,
    currentPoints: student.studyPoints || 0,
    adjustType: 'ADD',
    points: 10,
    reason: ''
  }
  adjustPointsDialogVisible.value = true
}

// 提交积分调整
const submitPointsAdjustment = async () => {
  if (!pointsAdjustFormRef.value) return

  await pointsAdjustFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const requestData = {
          userId: pointsAdjustForm.value.studentId,
          points: pointsAdjustForm.value.adjustType === 'ADD' 
            ? pointsAdjustForm.value.points 
            : -pointsAdjustForm.value.points,
          transactionType: 'ADMIN_ADJUST',
          description: pointsAdjustForm.value.reason
        }

        await request.post('/api/study/points/admin/adjust', requestData)
        ElMessage.success('积分调整成功')
        adjustPointsDialogVisible.value = false
        fetchStudents() // 重新获取学生列表
      } catch (error) {
        ElMessage.error('积分调整失败')
      }
    }
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchStudents()
})
</script>

<style scoped>
.student-points-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.points-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.points-value {
  font-weight: bold;
  color: #e6a23c;
  font-size: 16px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>